package com.hjm.project.retainRewards.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.hjm.common.utils.StringUtils;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.ActActive.ActActive.domain.ActActive;
import com.hjm.project.ActActive.ActActive.mapper.ActActiveMapper;
import com.hjm.project.ActStage.ActStage.mapper.ActStageMapper;
import com.hjm.project.actTransactionCompliance.compliance.mapper.ActTransactionComplianceMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hjm.project.retainRewards.mapper.RetainRewardsMapper;
import com.hjm.project.retainRewards.domain.RetainRewards;
import com.hjm.project.retainRewards.service.IRetainRewardsService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 奖励留存Service业务层处理
 * 
 * @author maker-platform
 * @date 2024-04-15
 */
@Service
public class RetainRewardsServiceImpl implements IRetainRewardsService {
    @Resource
    private RetainRewardsMapper retainRewardsMapper;
    @Autowired
    private ActStageMapper actStageMapper;
    @Resource
    private ActActiveMapper actActiveMapper;
    @Autowired
    private ActTransactionComplianceMapper actTransactionComplianceMapper;

    /**
     * 查询奖励留存
     * 
     * @param id 奖励留存ID
     * @return 奖励留存
     */
    @Override
    public RetainRewards selectRetainRewardsById(Integer id) {
        return retainRewardsMapper.selectRetainRewardsById(id);
    }

    /**
     * 查询奖励留存列表
     * 
     * @param retainRewards 奖励留存
     * @return 奖励留存
     */
    @Override
    public List<RetainRewards> selectRetainRewardsList(RetainRewards retainRewards) {
        return retainRewardsMapper.selectRetainRewardsList(retainRewards);
    }

    /**
     * 查询奖励留存列表
     *
     * @param retainRewards 奖励留存
     * @return 奖励留存 一个结果
     */
    @Override
    public RetainRewards selectRetainRewardsOne(RetainRewards retainRewards) {
        return retainRewardsMapper.selectRetainRewardsOne(retainRewards);
    }

    /**
     * 新增奖励留存
     * 
     * @param retainRewards 奖励留存
     * @return 结果
     */
    @Override
    public int insertRetainRewards(RetainRewards retainRewards) {
        String actId = retainRewards.getActId();
        String agentNum = retainRewards.getAgentNum();
        //获取活动得服务费，流量费金额
        ActActive actActive = actActiveMapper.selectActActiveById(retainRewards.getActId().toString());

        String simFeeReturn = actActive.getSimFeeReturn();
        String simFeeKeep = actActive.getSim_fee_keep();

        String serviceFeeReturn = actActive.getServiceFeeReturn();
        String serviceFeeKeep = actActive.getService_fee_keep();
        //流量费
        RetainRewards ri = new RetainRewards();
        ri.setActId(actId);
        ri.setAgentNum(agentNum);
        ri.setTotalValue(new BigDecimal(simFeeReturn));
        ri.setRetainedValue(new BigDecimal(simFeeKeep));
        ri.setType(1);
        RetainRewards result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "1");
        if (result == null) {
            retainRewardsMapper.insertRetainRewards(ri);
        } else {
            retainRewardsMapper.insertRetainRewardsRecord(result);
            retainRewardsMapper.updateRetainRewards(ri);
        }

        //服务费
        ri.setTotalValue(new BigDecimal(serviceFeeReturn));
        ri.setRetainedValue(new BigDecimal(serviceFeeKeep));
        ri.setType(2);
        result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "2");
        if (result == null) {
            retainRewardsMapper.insertRetainRewards(ri);
        } else {
            retainRewardsMapper.insertRetainRewardsRecord(result);
            retainRewardsMapper.updateRetainRewards(ri);
        }


        //阶段信息
        Map params = new HashMap<>();
        params.put("act_id",actId);
        List<Map<String, Object>> actTransactionCompliance = actTransactionComplianceMapper.getActTransactionCompliance(params);
        for (Map<String, Object> data : actTransactionCompliance) {
            Map<String, Object> stageParams = new HashMap<>();
            stageParams.put("stage_id",data.get("STAGE_ID"));
            List<Map<String, Object>> actStage = actStageMapper.getActStageList(stageParams);
            for (Map<String, Object> objectMap : actStage) {
                Integer stage = Integer.parseInt(objectMap.get("STAGE").toString());
                String matching_num = objectMap.get("MATCHING_NUM").toString();
                String keep_money = objectMap.get("KEEP_MONEY").toString();
                if (stage == 1) {
                    //激活
                    ri.setTotalValue(new BigDecimal(matching_num));
                    ri.setRetainedValue(new BigDecimal(keep_money));
                    ri.setStage(stage);
                    ri.setType(3);
                    result = retainRewardsMapper.selectRetainRewardsByStage(actId, agentNum, "3",stage.toString());
                    if (result == null) {
                        retainRewardsMapper.insertRetainRewards(ri);
                    } else {
                        retainRewardsMapper.insertRetainRewardsRecord(result);
                        retainRewardsMapper.updateRetainRewards(ri);
                    }
                } else if (stage == 2){
                    //激活
                    ri.setTotalValue(new BigDecimal(matching_num));
                    ri.setRetainedValue(new BigDecimal(keep_money));
                    ri.setStage(stage);
                    ri.setType(4);
                    result = retainRewardsMapper.selectRetainRewardsByStage(actId, agentNum, "4",stage.toString());
                    if (result == null) {
                        retainRewardsMapper.insertRetainRewards(ri);
                    } else {
                        retainRewardsMapper.insertRetainRewardsRecord(result);
                        retainRewardsMapper.updateRetainRewards(ri);
                    }
                } else if (stage > 2){
                    //激活
                    ri.setTotalValue(new BigDecimal(matching_num));
                    ri.setRetainedValue(new BigDecimal(keep_money));
                    ri.setStage(stage);
                    ri.setType(5);
                    result = retainRewardsMapper.selectRetainRewardsByStage(actId, agentNum, "5",stage.toString());
                    if (result == null) {
                        retainRewardsMapper.insertRetainRewards(ri);
                    } else {
                        retainRewardsMapper.insertRetainRewardsRecord(result);
                        retainRewardsMapper.updateRetainRewards(ri);
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 修改奖励留存
     * 
     * @param retainRewards 奖励留存
     * @return 结果
     */
    @Override
    public int updateRetainRewards(RetainRewards retainRewards) {
        return retainRewardsMapper.updateRetainRewards(retainRewards);
    }

    /**
     * 删除奖励留存对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteRetainRewardsByIds(String ids) {
        return retainRewardsMapper.deleteRetainRewardsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除奖励留存信息
     * 
     * @param id 奖励留存ID
     * @return 结果
     */
    @Override
    public int deleteRetainRewardsById(Integer id) {
        return retainRewardsMapper.deleteRetainRewardsById(id);
    }

    @Override
    public RetainRewards selectRetainRewardsBy(Integer actId, String agentNum, String number) {
        return retainRewardsMapper.selectRetainRewardsBy(actId.toString(),agentNum,number);
    }

    @Override
    public RetainRewards selectRetainRewardsByStage(Integer actId, String agentNum, String number, String stage) {
        return retainRewardsMapper.selectRetainRewardsByStage(actId.toString(),agentNum,number,stage);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertRetainRewardsAgent(JSONObject body) {
        String actId = body.getString("actId");
        String agentNum = body.getString("agentNum");
        //获取活动得服务费，流量费金额
        ActActive actActive = actActiveMapper.selectActActiveById(actId.toString());
        if (actActive == null) {
            return AjaxResult.success("活动信息不存在");
        }


        String llf_money = body.getString("llf_money");
        String llf_lc_money = body.getString("llf_lc_money");
        String my_llf_lc_money = body.getString("my_llf_lc_money");
        if (StringUtils.isBlank(my_llf_lc_money)) {
            return AjaxResult.error("流量费留存金额不可为空");
        }

        //流量费
        RetainRewards ri = new RetainRewards();
        ri.setActId(actId);
        ri.setAgentNum(agentNum);
        ri.setTotalValue(new BigDecimal(llf_money));
        ri.setRetainedValue(new BigDecimal(my_llf_lc_money));
        if (ri.getRetainedValue().compareTo(new BigDecimal(llf_lc_money)) == 1) {
            return AjaxResult.error("流量费留存金额不可大于活动设置金额");
        }

        ri.setType(1);
        RetainRewards result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "1");
        if (result == null) {
            retainRewardsMapper.insertRetainRewards(ri);
        } else {
            retainRewardsMapper.insertRetainRewardsRecord(result);
            retainRewardsMapper.updateRetainRewards(ri);
        }

        String fwf_money = body.getString("fwf_money");
        String fwf_lc_money = body.getString("fwf_lc_money");
        String my_fwf_lc_money = body.getString("my_fwf_lc_money");
        if (StringUtils.isBlank(my_fwf_lc_money)) {
            return AjaxResult.error("服务费留存金额不可为空");
        }

        //服务费
        ri.setTotalValue(new BigDecimal(fwf_money));
        ri.setRetainedValue(new BigDecimal(my_fwf_lc_money));
        if (ri.getRetainedValue().compareTo(new BigDecimal(fwf_lc_money)) == 1) {
            return AjaxResult.error("服务费留存金额不可大于活动设置金额");
        }
        ri.setType(2);
        result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "2");
        if (result == null) {
            retainRewardsMapper.insertRetainRewards(ri);
        } else {
            retainRewardsMapper.insertRetainRewardsRecord(result);
            retainRewardsMapper.updateRetainRewards(ri);
        }

        //激活
        String jh_money = body.getString("jh_money");
        String jh_lc_money = body.getString("jh_lc_money");
        String my_jh_lc_money = body.getString("my_jh_lc_money");

        if (StringUtils.isBlank(my_jh_lc_money)) {
            return AjaxResult.error("激活留存金额不可为空");
        }
        ri.setTotalValue(new BigDecimal(jh_money));
        ri.setRetainedValue(new BigDecimal(my_jh_lc_money));
        if (ri.getRetainedValue().compareTo(new BigDecimal(jh_lc_money)) == 1) {
            return AjaxResult.error("激活留存金额不可大于活动设置金额");
        }
        ri.setStage(1);
        ri.setType(3);
        result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "3");
        if (result == null) {
            retainRewardsMapper.insertRetainRewards(ri);
        } else {
            retainRewardsMapper.insertRetainRewardsRecord(result);
            retainRewardsMapper.updateRetainRewards(ri);
        }

        //达标
        if (StringUtils.isNotBlank(body.getString("db_money"))) {
            String db_money = body.getString("db_money");
            String db_lc_money = body.getString("db_lc_money");
            String my_db_lc_money = body.getString("my_db_lc_money");
            if (StringUtils.isBlank(my_db_lc_money)) {
                return AjaxResult.error("达标留存金额不可为空");
            }

            ri.setTotalValue(new BigDecimal(db_money));
            ri.setRetainedValue(new BigDecimal(my_db_lc_money));
            if (ri.getRetainedValue().compareTo(new BigDecimal(db_lc_money)) == 1) {
                return AjaxResult.error("达标留存金额不可大于活动设置金额");
            }
            ri.setStage(2);
            ri.setType(4);
            result = retainRewardsMapper.selectRetainRewardsBy(actId, agentNum, "4");
            if (result == null) {
                retainRewardsMapper.insertRetainRewards(ri);
            } else {
                retainRewardsMapper.insertRetainRewardsRecord(result);
                retainRewardsMapper.updateRetainRewards(ri);
            }
        }

        List<JSONObject> list = JSONObject.parseArray(body.getString("stageList"), JSONObject.class);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.success();
        }

        for (JSONObject data : list) {
            Integer stage = data.getInteger("stage") + 2;
            Integer newStage = data.getInteger("stage") + 2;
            String jd_money = data.getString("jd_money");
            String jd_lc_money = data.getString("jd_lc_money");
            String my_jd_lc_money = data.getString("my_jd_lc_money");
            if (StringUtils.isBlank(my_jd_lc_money)) {
                return AjaxResult.error("第" + (stage - 2) + "阶段留存金额不可为空");
            }

            ri.setTotalValue(new BigDecimal(jd_money));
            ri.setRetainedValue(new BigDecimal(my_jd_lc_money));
            ri.setStage(newStage);
            if (ri.getRetainedValue().compareTo(new BigDecimal(jd_lc_money)) == 1) {
                return AjaxResult.error("第" + (stage - 2) + "阶段留存金额不可大于活动设置金额");
            }

            ri.setType(5);
            result = retainRewardsMapper.selectRetainRewardsByStage(actId, agentNum, "5",newStage.toString());
            if (result == null) {
                retainRewardsMapper.insertRetainRewards(ri);
            } else {
                retainRewardsMapper.insertRetainRewardsRecord(result);
                retainRewardsMapper.updateRetainRewardsStage(ri);
            }

        }
        return AjaxResult.success();
    }
}
